package com.yxn.cloud.product.exception;

import com.cloud.common.exception.BisCodeEnum;
import com.yxn.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author lisw
 * @create 2021/6/28 17:14
 * 处理 com.yxn.cloud.product.controller 下所有controller抛出的异常
 */
@RestControllerAdvice(value = "com.yxn.cloud.product.controller")
@Slf4j
public class ControllerAdviceException {

    /**
     * 用来处理全局异常类
     * @param e 捕获异常类型
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handle(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        HashMap<String, Object> map = new HashMap<>(8);
        result.getFieldErrors().forEach((fieldError) -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BisCodeEnum.VALID_EXCEPTION.getCode(), BisCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R ExceptionHandle(Exception e){
        System.out.println(e.getMessage());
        return R.error(BisCodeEnum.UNKNOWN_EXCEPTION.getCode(), BisCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }


}
